package com.villaday.idf.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.villaday.idf.AppContext;
import com.villaday.idf.MainActivity;
import com.villaday.idf.activity.BourbonListActivity;
import com.villaday.idf.activity.CashWithdrawalActivity;
import com.villaday.idf.activity.H5Activity;
import com.villaday.idf.activity.HouseDetailsActivityFor3;
import com.villaday.idf.activity.InviteFriendActivity;
import com.villaday.idf.activity.MyOrderDetailActivity;
import com.villaday.idf.activity.SearchBournActivity;
import com.villaday.idf.util.LogeUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyJPushReceiver extends BroadcastReceiver {
    private static final String TAG = "JIGUANG-Example";

    @Override
    public void onReceive(Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            LogeUtil.e(TAG, "[MyJPushReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                LogeUtil.e(TAG, "[MyJPushReceiver] 接收Registration Id : " + regId);
                AppContext.JPushId = regId;
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                LogeUtil.e(TAG, "[MyJPushReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                processCustomMessage(context, bundle);

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
                LogeUtil.e(TAG, "[MyJPushReceiver] 接收到推送下来的通知");
                int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                LogeUtil.e(TAG, "[MyJPushReceiver] 接收到推送下来的通知的ID: " + notifactionId);

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                LogeUtil.e(TAG, "[MyJPushReceiver] 用户点击打开了通知");


				/*//打开自定义的Activity
				Intent i = new Intent(context, TestActivity.class);
				i.putExtras(bundle);
				//i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
				context.startActivity(i);*/
                String title = bundle.getString("cn.jpush.android.NOTIFICATION_CONTENT_TITLE");

                String EXTRA1 = bundle.getString("cn.jpush.android.EXTRA");

                LogeUtil.e("EXTRA1", EXTRA1);
                Gson gson = new GsonBuilder().create();


                if (EXTRA1 != null) {
                    if (EXTRA1.length() == 2) {
                        Intent intent1 = new Intent(context, MainActivity.class);
                        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        context.startActivity(intent1);
                    } else {
                        Recevier EXTRA = gson.fromJson(EXTRA1, Recevier.class);

                        int type = EXTRA.getUserinfo().getType();

                        // "type": integer, 0无跳转，1跳转APP页面，2链接跳转内嵌webView,3 版本更新
                        if (type == 1) {
                            //跳转APP页面
                /*
                *   "idfAppPage": string, 定义的页面路径,
                    "params": {
                     id: "xxxxxx", app页面对应的参数，后期根据需要补充
                               },
                * */

                            if ("page/home".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/home";  首页

                                Intent intent1 = new Intent(context, MainActivity.class);
                                intent1.putExtra("type", "page/home");
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);


                            } else if ("page/home/material".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/home/material";  首页-动态(material)
                                Intent intent1 = new Intent(context, MainActivity.class);

                                intent1.putExtra("type", "page/home/material");
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);

                            } else if ("page/home/presell".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/home/presell";  首页-特卖(presell)
                                Intent intent1 = new Intent(context, MainActivity.class);
                                intent1.putExtra("type", "page/home/presell");
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);

                            } else if ("page/home/topic".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/home/topic";  首页-发现(topic)
                                Intent intent1 = new Intent(context, MainActivity.class);
                                intent1.putExtra("type", "page/home/topic");
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);

                            } else if ("page/village".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/village";  目的地列表页
                                Intent intent1 = new Intent(context, MainActivity.class);

                                intent1.putExtra("type", "page/village");
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);


                            } else if ("page/village/detail".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/village/detail";  目的地详情页
                                Intent intent1 = new Intent(context, BourbonListActivity.class);

                                intent1.putExtra("villageId", EXTRA.getUserinfo().getParams().getId());
                                intent1.putExtra("city", "");
                                intent1.putExtra("area", "");
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);
                            } else if ("page/search".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/search";  房源搜索索引页

                                Intent intent1 = new Intent(context, SearchBournActivity.class);
                                intent1.putExtra("cityId", EXTRA.getUserinfo().getParams().getId());
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);
                            } else if ("page/search/result".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/search/result";  房源搜索结果页
                                Intent intent1 = new Intent(context, BourbonListActivity.class);
                                intent1.putExtra("villageId", EXTRA.getUserinfo().getParams().getId());
                                intent1.putExtra("city", "");
                                intent1.putExtra("area", "");
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);
                            } else if ("page/house/detail".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/house/detail";  房源详情页
                                //普通房源
                                Intent intent1 = new Intent(context, HouseDetailsActivityFor3.class);
                                intent1.putExtra("houseId", EXTRA.getUserinfo().getParams().getId());
                                intent1.putExtra("persellId", "");
//                    intent.putExtra("type", data.get(position).getType());
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);

                            } else if ("page/presell/detail".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/presell/detail";  房源详情页
                                //特卖房源
                                Intent intent1 = new Intent(context, HouseDetailsActivityFor3.class);
                                intent1.putExtra("houseId", EXTRA.getUserinfo().getParams().getId());
                                intent1.putExtra("persellId", EXTRA.getUserinfo().getParams().getId());
                                intent1.putExtra("presellProduct", true);
//                    intent.putExtra("type", data.get(position).getType());
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);

                            } else if ("page/vip".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/vip";  VIP
                                Intent intent1 = new Intent(context, MainActivity.class);
                                intent1.putExtra("type", "page/vip");
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);

                            } else if ("page/vip/share".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/vip/share";  vip邀请好友分享页
                                Intent intent1 = new Intent(context, InviteFriendActivity.class);
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);

                            } else if ("page/vip/draw".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/vip/draw";  vip提款页
                                Intent intent1 = new Intent(context, CashWithdrawalActivity.class);

                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);

                            } else if ("page/member".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/member";  我的
                                Intent intent1 = new Intent(context, MainActivity.class);
                                intent1.putExtra("type", "page/member");
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);

                            } else if ("page/member/order".equals(EXTRA.getUserinfo().getIdfAppPage())) {
                                //"page/member/order";  我的订单

                                Intent intent1 = new Intent(context, MyOrderDetailActivity.class);
                                intent1.putExtra("orderNo", EXTRA.getUserinfo().getParams().getId());
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);
                            }else {

                                Intent intent1 = new Intent(context, MainActivity.class);
                                intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                context.startActivity(intent1);
                            }


                        } else if (type == 2) {
                            //链接跳转内嵌webView

                            Intent intent1 = new Intent(context, H5Activity.class);
                            intent1.putExtra("title", title + "");
                            intent1.putExtra("url", EXTRA.getUserinfo().getLink());
                            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                            context.startActivity(intent1);

                        } else if (type == 3) {
                            //版本更新
                            Intent intent1 = new Intent(context, MainActivity.class);
                            intent1.putExtra("type", "page/home");
                            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                            context.startActivity(intent1);
                        } else {

                            Intent intent1 = new Intent(context, MainActivity.class);
                            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                            context.startActivity(intent1);
                        }
                    }


                } else {

                    Intent intent1 = new Intent(context, MainActivity.class);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    context.startActivity(intent1);
                }


            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                LogeUtil.e(TAG, "[MyJPushReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                LogeUtil.e(TAG, "[MyJPushReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                LogeUtil.e(TAG, "[MyJPushReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {

        }

    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    LogeUtil.e(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + " - " + json.optString(myKey) + "]");
                    }
                } catch (JSONException e) {
                    LogeUtil.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.get(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
		/*if (MainActivity.isForeground) {
			String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
			String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
			Intent msgIntent = new Intent(MainActivity.MESSAGE_RECEIVED_ACTION);
			msgIntent.putExtra(MainActivity.KEY_MESSAGE, message);
			if (!ExampleUtil.isEmpty(extras)) {
				try {
					JSONObject extraJson = new JSONObject(extras);
					if (extraJson.length() > 0) {
						msgIntent.putExtra(MainActivity.KEY_EXTRAS, extras);
					}
				} catch (JSONException e) {

				}

			}
			LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
		}*/
    }
}
